//
//  HomeCardStore.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/8/7.
//

import Foundation
import SwiftUI

enum SignType: String, CaseIterable, Identifiable {
    case spo2
    case sleep
    case weight
    case pressure
    case physiologicalCycle
    case drinkWaterReminder
    case header // 组头，非实际卡片
    
    var id: String { rawValue }
    
    var name: String {
        switch self {
        case .spo2: return "血氧饱和度"
        case .sleep: return "睡眠"
        case .weight: return "体重"
        case .pressure: return "压力"
        case .physiologicalCycle: return "生理周期"
        case .drinkWaterReminder: return "喝水提醒"
        case .header: return "不显示在首页"
        }
    }
    
    var icon: String {
        switch self {
        case .spo2: return "card_spo2"
        case .sleep: return "card_sleep"
        case .weight: return "card_weight"
        case .pressure: return "card_pressure"
        case .physiologicalCycle: return "card_physiological_cycle"
        case .drinkWaterReminder: return "card_drink"
        case .header: return ""
        }
    }
    static let homeOrder: [SignType] = [.spo2, .sleep, .pressure, .weight]
}

@MainActor
final class CardStore: ObservableObject {
    @AppStorage("fullOrder") private var fullOrder: String = {
        // 默认顺序：首页卡片 + 非首页卡片 + 组头
        let home = SignType.homeOrder
        let forbidden: [SignType] = [.header] + home
        let rest = SignType.allCases.filter { !forbidden.contains($0) }
        return (home + [.header] + rest).map(\.rawValue).joined(separator: ",")
    }()
    
    /// 对外：完整顺序（含组头）
    var orderedCards: [SignType] {
        get { fullOrder.split(separator: ",").compactMap { SignType(rawValue: String($0)) } }
        set { fullOrder = newValue.map(\.rawValue).joined(separator: ",") }
    }
    
    /// 把「组头」放到正确位置：紧跟首页卡片
    func normalizeHeader(in list: [SignType]) -> [SignType] {
        let homeEnd = list.firstIndex(of: .header) ?? list.count
        var new = list.filter { $0 != .header }
        if homeEnd <= SignType.homeOrder.count {
            new.insert(.header, at: SignType.homeOrder.count)
        } else {
            new.append(.header)
        }
        return new
    }
}
